package com.sudo.rpc.server.task.registry;

import com.sudo.rpc.api.model.RegistryBean;
import com.sudo.rpc.api.model.RegistryMethod;
import com.sudo.rpc.api.model.RegistryServer;
import com.sudo.rpc.server.annotation.Note;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class BaseTaskRegistry {
    final private static Map<String, Class<?>> beanClassMap = new HashMap<>();

    public BaseTaskRegistry() {
    }

    public static void setModuleClassMap(Class<?> aClass){
        beanClassMap.put(StringUtils.uncapitalize(aClass.getSimpleName()), aClass);
    }

    public static void setModuleClassMap(String key, Class<?> aClass){
        beanClassMap.put(key, aClass);
    }

    public static Class<?> getClassByBean(String beanName){
        return beanClassMap.get(beanName);
    }

    public static RegistryServer getRegistryServer(){
        RegistryServer registryServer = new RegistryServer();
        List<RegistryBean> registryBeanList = new ArrayList<>();
        beanClassMap.forEach((k,v) -> {
            RegistryBean registryBean = new RegistryBean();
            registryBean.setBeanName(k);
            Method[] declaredMethods = v.getDeclaredMethods();
            if (declaredMethods.length == 0){
                return;
            }
            List<RegistryMethod> registryMethodList = new ArrayList<>();
            for (Method method : declaredMethods) {
                boolean notePresent = method.isAnnotationPresent(Note.class);
                if (notePresent) {
                    Note annotation = method.getAnnotation(Note.class);
                    RegistryMethod registryMethod = new RegistryMethod();
                    registryMethod.setMethodName(method.getName());
                    registryMethod.setMethodParams(annotation.params());
                    registryMethod.setDesc(annotation.desc());
                    registryMethodList.add(registryMethod);
                }
            }
            registryBean.setRegistryMethodList(registryMethodList);
            registryBeanList.add(registryBean);
        });
        registryServer.setBeanList(registryBeanList);
        return registryServer;
    }
}
